<?php
class MessagesController extends AppController {
	public $uses = array('Thread','Message','Follow','User');

	public function index(){

	}

	public function follow(){
		$this->layout = 'ajax';
		$data = $this->Follow->query("SELECT `Follow`.`from`, `Follow`.`to`, `Follow`.`id`, `User`.`id`, `User`.`username`, `User`.`url` FROM `foodies`.`follow` AS `Follow` LEFT JOIN `foodies`.`user` AS `User` ON (`Follow`.`to` = `User`.`id`) WHERE `Follow`.`from` = {$this->Session->read('userid')}");
		$this->set('data',$data);
	}

	public function thread(){
		$this->layout = 'ajax';
		
		$userid       = $this->Session->read('userid');
		$data         = $this->Thread->query("SELECT `Thread`.`id`, `Thread`.`user1`, `Thread`.`user2`, `Thread`.`count`, `user1`.`id`, `user1`.`username`, `user1`.`url`, `user2`.`id`, `user2`.`username`, `user2`.`url` FROM `foodies`.`Thread` AS `Thread` LEFT JOIN `foodies`.`user` AS `user1` ON (`Thread`.`user1` = `user1`.`id`) LEFT JOIN `foodies`.`user` AS `user2` ON (`Thread`.`user2` = `user2`.`id`) WHERE ((`user1` = {$userid}) OR (`user2` = {$userid}))");

		$this->set('data',$data);
	}

	public function detail($threadId = null){
		$this->layout = 'ajax';

		$data = $this->Message->find('all',
			array(
				'conditions' => array(
					'threadId' => $threadId
				)
			)
		);

		$this->set('data',$data);
	}

	public function post($toUserId){
		$this->layout = 'ajax';


        if ($this->request->is('post')) {
			$userid = $this->Session->read('userid');
			$user1  = $userid;
			$user2  = $toUserId;
			if ($userid > $toUserId){
				$user1 = $toUserId;
				$user2 = $userid;
			}

			$result = $this->Thread->find('first',
				array('conditions'=>array('user1' => $user1,'user2' => $user2))
			);

			if ($result) {
				$this->request->data['Message']['threadId'] = $result['Thread']['id'];
			}else{
				$newThread['user1'] = $user1;
				$newThread['user2'] = $user2;
				$this->Thread->save($newThread);
				$this->request->data['Message']['threadId'] = $this->Thread->id;
			}

			$this->request->data['Message']['userid']      = $userid;
			$this->request->data['Message']['createdTime'] = date('Y-m-d H:i:s');
			$this->Message->save($this->request->data['Message']);
        }

        $ret['result'] = true;
		$this->set('data',$ret);
	}

	public function postBox($toUserId){
		$this->layout = 'noStyle';
		$data = $this->User->findById($toUserId);
		$this->set('data',$data);
	}

}
?>                                                                                                                                                                                               